package com.atgouwu.mall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器: 解决feign远程调用丢失请求头,feign会新建请求(没请求头数据),被调用者从request中获取session等获取不到
 */
@Configuration
public class MyFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); //用RequestContextHolder拿刚来的请求数据
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest(); //老请求
                    if (request != null) {
                        String cookie = request.getHeader("Cookie"); //同步请求头数据(主要是cookie),把老请求cookie值放到新请求上
                        template.header("Cookie", cookie);
                    }
                }
            }
        };
        return requestInterceptor;
    }

}
